// 教师端交互脚本
(function(){
    // API_BASE变量已废弃，所有调用应使用相对路径
    const tokenKey = 'userToken';

    // 简单的HTTP封装
    async function http(url, options={}){
        // 自动添加token到请求头
        const userInfo = JSON.parse(localStorage.getItem('userInfo')||'{}');
        const token = userInfo.token;
        
        console.log('HTTP请求 - URL:', url);
        console.log('HTTP请求 - 当前userInfo:', userInfo);
        console.log('HTTP请求 - 当前token:', token);
        console.log('HTTP请求 - token类型:', typeof token);
        console.log('HTTP请求 - token长度:', token ? token.length : 0);
        
        const headers = Object.assign({
            'Content-Type':'application/json'
        }, options.headers||{});
        
        // 如果有token，添加到Authorization头
        if (token) {
            headers['Authorization'] = token;
            console.log('HTTP请求 - 已添加Authorization头:', token);
        } else {
            console.warn('HTTP请求 - 没有token，Authorization头未添加');
        }
        
        console.log('HTTP请求 - 最终请求头:', headers);
        
        const res = await fetch(url, Object.assign({}, options, { headers }));
        if(!res.ok){
            const text = await res.text().catch(()=> '');
            throw new Error(text || `HTTP ${res.status}`);
        }
        const ct = res.headers.get('content-type')||'';
        if(ct.includes('application/json')) return res.json();
        return res.text();
    }

    // 简单的消息提示
    function showMsg(el, msg, type='info'){
        el.textContent = msg;
        el.className = `message ${type}`;
        el.style.display = 'block';
        setTimeout(()=>{ el.style.display='none'; }, 4000);
    }

    // 页面初始化
    document.addEventListener('DOMContentLoaded', ()=>{
        console.log('页面初始化开始...');
        
        // 检查当前页面类型
        const isMainPage = window.location.pathname.includes('/teacher/schedule') || 
                          window.location.pathname.includes('/index.html') ||
                          window.location.pathname === '/teacher/schedule';
        
        console.log('当前页面类型:', isMainPage ? '主页面' : '独立页面');
        
        // 所有页面都需要初始化用户信息
        initUser();
        
        // 只在主页面执行菜单相关逻辑
        if (isMainPage) {
            bindMenu();
            initProfile();
            initSchedule();
            bindPasswordForm();
            bindStudents();
            bindUpload();
            bindDownload();
            bindFeedback();
            
            // 根据URL哈希切换到对应视图
            applyHashView();
            window.addEventListener('hashchange', applyHashView);
        }
        
        // 绑定退出登录按钮事件（所有页面都需要）
        const logoutBtn = document.getElementById('logoutBtn');
        if (logoutBtn) {
            console.log('找到退出登录按钮，绑定点击事件');
            logoutBtn.addEventListener('click', function(e) {
                console.log('退出登录按钮被点击');
                e.preventDefault();
                logout();
            });
            console.log('退出登录按钮事件绑定完成');
        } else {
            console.error('未找到退出登录按钮！');
        }

        console.log('页面初始化完成');
    });

    // 初始化用户信息
    function initUser(){
        const userInfo = JSON.parse(localStorage.getItem('userInfo')||'{}');
        
        // 检查用户是否已登录 - 更严格的验证
        if (!userInfo || !userInfo.token || !userInfo.userDTO || 
            typeof userInfo.token !== 'string' || userInfo.token.trim() === '') {
            console.log('用户未登录或token无效，跳转到登录页');
            // 清除可能存在的无效数据
            localStorage.removeItem('userInfo');
            localStorage.removeItem('userToken');
            window.location.href = 'login.html';
            return;
        }
        
        // 验证token格式（简单验证）
        if (userInfo.token.length < 10) {
            console.log('Token格式无效，跳转到登录页');
            localStorage.removeItem('userInfo');
            localStorage.removeItem('userToken');
            window.location.href = 'login.html';
            return;
        }
        
        // 获取用户信息
        const userDTO = userInfo.userDTO;
        if (!userDTO || !userDTO.id) {
            console.log('用户信息不完整，跳转到登录页');
            localStorage.removeItem('userInfo');
            localStorage.removeItem('userToken');
            window.location.href = 'login.html';
            return;
        }
        
        const name = userDTO.nickName || userDTO.account || '教师';
        const avatar = userDTO.icon || '';
        
        // 显示用户姓名
        const teacherNameElement = document.getElementById('teacher-name');
        if (teacherNameElement) {
            teacherNameElement.textContent = name;
        }
        
        // 显示用户头像
        const avatarElement = document.getElementById('user-avatar');
        if (avatarElement) {
            if (avatar) {
                avatarElement.src = avatar;
                avatarElement.alt = name + '的头像';
            } else {
                // 如果没有头像，显示默认头像（使用用户名首字母）
                avatarElement.src = '';
                avatarElement.style.background = 'linear-gradient(135deg, #667eea, #764ba2)';
                avatarElement.style.display = 'flex';
                avatarElement.style.alignItems = 'center';
                avatarElement.style.justifyContent = 'center';
                avatarElement.style.color = 'white';
                avatarElement.style.fontWeight = 'bold';
                avatarElement.style.fontSize = '14px';
                avatarElement.textContent = name.charAt(0).toUpperCase();
                avatarElement.alt = name + '的头像';
            }
        }
        
        console.log('用户信息加载成功:', { name, avatar, permission: userDTO.permission });
    }

    function bindMenu(){
        // 对于新创建的教师端页面，菜单跳转由页面内联脚本处理
        // 这里只处理原有的单页应用逻辑
        const menu = document.getElementById('menu');
        const title = document.getElementById('view-title');
        
        // 检查是否在新创建的教师端页面中
        const isNewTeacherPage = window.location.pathname.includes('/teacher/');
        if (isNewTeacherPage) {
            console.log('在新创建的教师端页面中，菜单跳转由页面内联脚本处理');
            return;
        }
        
        menu.addEventListener('click', (e)=>{
            const btn = e.target.closest('.menu-item');
            if(!btn) return;
            [...menu.querySelectorAll('.menu-item')].forEach(i=> i.classList.remove('active'));
            btn.classList.add('active');
            const view = btn.getAttribute('data-view');
            const url = btn.getAttribute('data-url');
            title.textContent = btn.textContent;
            
            // 更新URL后缀
            updateURL(url);
            
            // 切换视图
            switchView(view);
            
            // 根据视图加载相应数据
            if(view==='profile') loadProfile();
            else if(view==='schedule') loadSchedule();
        });
    }

    function switchView(view){
        [...document.querySelectorAll('.view')].forEach(v=> v.style.display='none');
        const target = document.getElementById(`view-${view}`);
        if(target) target.style.display = 'block';
    }

    // 根据URL hash 切换视图，如 #/schedule 或 #/students
    function applyHashView(){
        const hash = window.location.hash || '';
        const view = hash.replace(/^#\//, '') || 'profile';
        switchView(view);
        const titleEl = document.getElementById('view-title');
        const menu = document.getElementById('menu');
        if(menu){
            [...menu.querySelectorAll('.menu-item')].forEach(i=> i.classList.remove('active'));
            const btn = menu.querySelector(`[data-view="${view}"]`);
            if(btn){
                btn.classList.add('active');
                if(titleEl) titleEl.textContent = btn.textContent;
            }
        }
        if(view==='schedule') loadSchedule();
        if(view==='profile') loadProfile();
        if(view==='students') loadStudents();
    }

    // 更新URL后缀
    function updateURL(url) {
        if (url && url !== '/index') {
            // 如果不是默认页面，更新URL
            const newURL = window.location.pathname.replace(/\/[^\/]*$/, '') + url;
            window.history.pushState({}, '', newURL);
            console.log('URL已更新为:', newURL);
        } else {
            // 默认页面，使用基础URL
            const baseURL = window.location.pathname.replace(/\/[^\/]*$/, '');
            window.history.pushState({}, '', baseURL);
            console.log('URL已更新为默认页面:', baseURL);
        }
    }


    // ========== 教员信息及考勤 ==========
    function initProfile(){
        // 设置当前月份（若页面不存在相关DOM则直接跳过，避免阻断其他功能）
        const monthInput = document.getElementById('attendanceMonth');
        const refreshBtn = document.getElementById('refreshAttendance');
        if(!monthInput){
            return; // 非个人信息页/未包含考勤区块的页面
        }

        const now = new Date();
        const currentMonth = now.getFullYear() + '-' + String(now.getMonth() + 1).padStart(2, '0');
        monthInput.value = currentMonth;
        
        // 绑定刷新考勤按钮
        if (refreshBtn) {
            refreshBtn.addEventListener('click', loadAttendance);
        }
        
        // 初始加载教员信息
        loadProfile();
    }

    function loadProfile(){
        const userInfo = JSON.parse(localStorage.getItem('userInfo')||'{}');
        if (!userInfo.userDTO) return;
        
        const userDTO = userInfo.userDTO;
        
        // 显示个人信息
        document.getElementById('profile-name').textContent = userDTO.nickName || '未设置';
        document.getElementById('profile-account').textContent = `T${String(userDTO.id).padStart(4, '0')}`; // 生成教师编号
        document.getElementById('profile-permission').textContent = getPermissionText(userDTO.permission);
        
        // 设置创建时间为当前时间（模拟）
        const now = new Date();
        const createTime = new Date(now.getFullYear() - 2, now.getMonth(), now.getDate()); // 假设2年前入职
        document.getElementById('profile-create-time').textContent = createTime.toLocaleDateString('zh-CN');
        
        // 显示头像
        const profileAvatar = document.getElementById('profile-avatar');
        if (userDTO.icon && userDTO.icon.trim() !== '') {
            profileAvatar.src = userDTO.icon;
            profileAvatar.style.display = 'block';
            profileAvatar.style.background = 'none';
            profileAvatar.textContent = '';
        } else {
            // 默认头像 - 使用用户名首字母
            profileAvatar.src = '';
            profileAvatar.style.background = 'linear-gradient(135deg, #667eea, #764ba2)';
            profileAvatar.style.display = 'flex';
            profileAvatar.style.alignItems = 'center';
            profileAvatar.style.justifyContent = 'center';
            profileAvatar.style.color = 'white';
            profileAvatar.style.fontWeight = 'bold';
            profileAvatar.style.fontSize = '48px';
            profileAvatar.textContent = (userDTO.nickName || '教').charAt(0).toUpperCase();
        }
        
        // 加载考勤记录
        loadAttendance();
        
        console.log('教员信息加载成功:', userDTO);
    }

    function getPermissionText(permission) {
        switch(permission) {
            case 0: return '普通教师';
            case 1: return '班主任';
            case 2: return '年级主任';
            case 3: return '教务主任';
            case 4: return '管理员';
            default: return '未知';
        }
    }

    async function loadAttendance(){
        const month = document.getElementById('attendanceMonth').value;
        const tbody = document.getElementById('attendanceBody');
        const empty = document.getElementById('attendanceEmpty');
        
        tbody.innerHTML = '';
        empty.style.display = 'none';
        
        try {
            // 这里使用占位API，待后端实现后替换
            // 假设接口：GET /teacher/attendance?month=yyyy-MM
            // const res = await http(`${API_BASE}/teacher/attendance?month=${month}`);
            // const list = res.data || [];
            
            // 临时模拟数据
            const list = generateMockAttendanceData(month);
            
            if(!list.length) {
                empty.style.display = 'block';
                return;
            }
            
            // 统计考勤数据
            const stats = {
                total: list.length,
                normal: 0,
                late: 0,
                absent: 0
            };
            
            for(const item of list) {
                // 统计各种状态的数量
                stats[item.status]++;
                
                // 获取星期
                const date = new Date(item.date);
                const weekDay = getWeekDayText(date.getDay());
                
                const tr = document.createElement('tr');
                tr.innerHTML = `
                    <td>${item.date}</td>
                    <td>${weekDay}</td>
                    <td>${item.checkIn}</td>
                    <td>${item.checkOut}</td>
                    <td>${item.workHours}</td>
                    <td><span class="attendance-status status-${item.status}">${getStatusText(item.status)}</span></td>
                `;
                tbody.appendChild(tr);
            }
            
            // 更新统计信息
            updateAttendanceStats(stats);
            
        } catch(err) {
            empty.style.display = 'block';
            empty.textContent = '加载考勤记录失败，请稍后重试';
            console.error(err);
        }
    }

    function generateMockAttendanceData(month) {
        const [year, monthNum] = month.split('-').map(Number);
        const daysInMonth = new Date(year, monthNum, 0).getDate();
        const data = [];
        
        for(let day = 1; day <= daysInMonth; day++) {
            const date = new Date(year, monthNum - 1, day);
            const dayOfWeek = date.getDay();
            
            // 跳过周末
            if(dayOfWeek === 0 || dayOfWeek === 6) continue;
            
            // 更真实的考勤数据生成
            let status, checkIn, checkOut, workHours;
            const random = Math.random();
            
            if (random > 0.85) {
                // 15% 概率迟到
                status = 'late';
                checkIn = '08:30';
                checkOut = '17:00';
                workHours = '8.5小时';
            } else if (random > 0.95) {
                // 10% 概率缺勤
                status = 'absent';
                checkIn = '-';
                checkOut = '-';
                workHours = '-';
            } else {
                // 75% 概率正常
                status = 'normal';
                checkIn = '08:00';
                checkOut = '17:00';
                workHours = '9小时';
            }
            
            // 添加一些特殊日期处理
            const dayOfMonth = date.getDate();
            if (dayOfMonth === 1) {
                // 月初第一天，通常是正常
                status = 'normal';
                checkIn = '08:00';
                checkOut = '17:00';
                workHours = '9小时';
            }
            
            data.push({
                date: `${year}-${String(monthNum).padStart(2, '0')}-${String(day).padStart(2, '0')}`,
                checkIn,
                checkOut,
                workHours,
                status
            });
        }
        
        return data;
    }

    function getStatusText(status) {
        switch(status) {
            case 'normal': return '正常';
            case 'late': return '迟到';
            case 'absent': return '缺勤';
            default: return '未知';
        }
    }

    function getWeekDayText(day) {
        const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
        return weekDays[day];
    }

    function updateAttendanceStats(stats) {
        document.getElementById('total-days').textContent = stats.total;
        document.getElementById('normal-days').textContent = stats.normal;
        document.getElementById('late-days').textContent = stats.late;
        document.getElementById('absent-days').textContent = stats.absent;
    }

    // ========== 课表 ==========
    function initSchedule(){
        document.getElementById('refreshSchedule').addEventListener('click', loadSchedule);
        const datePicker = document.getElementById('datePicker');
        const today = new Date();
        datePicker.value = today.toISOString().slice(0,10);
        loadSchedule();
    }

    async function loadSchedule(){
        const empty = document.getElementById('scheduleEmpty');
        empty.style.display = 'none';

        const userInfo = JSON.parse(localStorage.getItem('userInfo')||'{}');
        const teacherId = userInfo.userDTO ? userInfo.userDTO.id : null;
        const date = document.getElementById('datePicker').value;

        if (!teacherId) {
            empty.style.display = 'block';
            empty.textContent = '用户信息获取失败，请重新登录';
            return;
        }

        try{
            // 调用真实接口获取教师课表（以周为单位）
            const res = await http(`/schedule/querySchedule?teacherId=${teacherId}&date=${date}`);
            const list = res.data || [];

            // 清空所有课程单元格
            clearScheduleGrid();
            
            // 显示周日期范围
            displayWeekDateRange(date);
            
            if(!list.length){ 
                empty.style.display='block'; 
                empty.textContent = '暂无课程安排';
                return; 
            }
            
            // 渲染课表数据
            renderScheduleData(list);
            
        }catch(err){
            empty.style.display='block';
            empty.textContent = '加载课表失败，请稍后重试';
            console.error('课表加载错误:', err);
        }
    }

    // 清空课表网格
    function clearScheduleGrid() {
        const timeSlots = ['1', '2', '3', '4'];
        const weekDays = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
        
        timeSlots.forEach(slot => {
            weekDays.forEach(day => {
                const cell = document.getElementById(`${day}-${slot}`);
                if (cell) {
                    cell.innerHTML = '';
                }
            });
        });
    }

    // 显示周日期范围
    function displayWeekDateRange(selectedDate) {
        const date = new Date(selectedDate);
        const weekStart = getWeekStart(date);
        const weekEnd = getWeekEnd(date);
        
        const dateRange = `${weekStart.toLocaleDateString('zh-CN')} - ${weekEnd.toLocaleDateString('zh-CN')}`;
        document.getElementById('weekDateRange').textContent = dateRange;
    }

    // 获取周开始日期（周一）
    function getWeekStart(date) {
        const day = date.getDay();
        const diff = date.getDate() - day + (day === 0 ? -6 : 1); // 调整为周一
        return new Date(date.setDate(diff));
    }

    // 获取周结束日期（周日）
    function getWeekEnd(date) {
        const weekStart = getWeekStart(new Date(date));
        const weekEnd = new Date(weekStart);
        weekEnd.setDate(weekStart.getDate() + 6);
        return weekEnd;
    }

    // 渲染课表数据
    function renderScheduleData(scheduleList) {
        scheduleList.forEach(item => {
            const date = new Date(item.teachDate || item.date);
            const weekDay = getWeekDay(date);
            const timeSlot = getTimeSlot(item.startTime || item.time);
            
            if (weekDay && timeSlot) {
                const cellId = `${weekDay}-${timeSlot}`;
                const cell = document.getElementById(cellId);
                if (cell) {
                    cell.innerHTML = createCourseItem(item);
                }
            }
        });
    }

    // 获取星期几
    function getWeekDay(date) {
        const weekDays = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
        return weekDays[date.getDay()];
    }

    // 获取时间段
    function getTimeSlot(time) {
        if (typeof time === 'string') {
            // 处理时间格式，支持多种格式
            const timeStr = time.toString();
            if (timeStr.includes('08:00') || timeStr.includes('09:35') || 
                timeStr.includes('08:00:00') || timeStr.includes('09:35:00')) return '1';
            if (timeStr.includes('10:00') || timeStr.includes('11:35') || 
                timeStr.includes('10:00:00') || timeStr.includes('11:35:00')) return '2';
            if (timeStr.includes('14:00') || timeStr.includes('15:35') || 
                timeStr.includes('14:00:00') || timeStr.includes('15:35:00')) return '3';
            if (timeStr.includes('16:00') || timeStr.includes('17:35') || 
                timeStr.includes('16:00:00') || timeStr.includes('17:35:00')) return '4';
        }
        return null;
    }

    // 创建课程项HTML
    function createCourseItem(item) {
        return `
            <div class="course-item" title="${item.note || ''}">
                <div class="course-name">${item.courseName || item.course || '课程'}</div>
                <div class="class-info">${item.className || item.clazz || '班级'}</div>
                <div class="location">${item.place || '地点'}</div>
            </div>
        `;
    }

    // ========== 修改密码 ==========
    function bindPasswordForm(){
        const form = document.getElementById('passwordForm');
        const msg = document.getElementById('passwordMsg');
        if (!form) return; // 非密码页面时跳过
        form.addEventListener('submit', async (e)=>{
            e.preventDefault();
            const oldPassword = (document.getElementById('oldPassword')?.value || '').trim();
            const newPassword = (document.getElementById('newPassword')?.value || '').trim();
            const confirmPassword = (document.getElementById('confirmPassword')?.value || '').trim();

            if(!oldPassword || !newPassword || !confirmPassword){
                showMsg(msg, '请完整填写', 'error'); return;
            }
            if(newPassword !== confirmPassword){
                showMsg(msg, '两次输入的新密码不一致', 'error'); return;
            }
            // 简单长度校验（可按需调整）
            if(newPassword.length < 6){
                showMsg(msg, '新密码长度不能少于6位', 'error'); return;
            }
            try{
                const submitBtn = form.querySelector('button[type="submit"]');
                if (submitBtn) { submitBtn.disabled = true; submitBtn.textContent = '提交中...'; }
                // 后端接口：POST /user/updatePassword  Authorization + JSON body
                console.log('准备调用修改密码接口:', '/user/updatePassword');
                console.log('请求体:', { oldPassWord: oldPassword, newPassWord: newPassword });
                
                // 获取用户token
                const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
                const token = userInfo.token;
                
                if (!token) {
                    showMsg(msg, '未找到用户token，请重新登录', 'error');
                    return;
                }
                
                console.log('调用修改密码接口:', `${API_BASE}/user/updatePassword`);
                
                // 调用后端接口
                const response = await fetch(`${API_BASE}/user/updatePassword`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': token
                    },
                    body: JSON.stringify({ oldPassWord: oldPassword, newPassWord: newPassword })
                });
                
                if (response.ok) {
                    const res = await response.json();
                    console.log('修改密码接口响应:', res);
                    
                    // 期望返回 { success: true/false, errorMsg?: string }
                    if (res && (res.success === true || res.code === 200)){
                        showMsg(msg, '密码修改成功', 'success');
                        form.reset();
                    } else {
                        const err = res?.errorMsg || res?.message || '修改失败';
                        showMsg(msg, err, 'error');
                    }
                } else {
                    const errorText = await response.text();
                    console.error('修改密码请求失败:', response.status, errorText);
                    showMsg(msg, `请求失败: ${response.status}`, 'error');
                }
            }catch(err){
                showMsg(msg, '修改失败：' + (err.message || err), 'error');
            }finally{
                const submitBtn = form.querySelector('button[type="submit"]');
                if (submitBtn) { submitBtn.disabled = false; submitBtn.textContent = '提交修改'; }
            }
        });
    }

    // ========== 学生信息 ==========
    function bindStudents(){
        document.getElementById('searchStudentBtn').addEventListener('click', loadStudents);
    }

    async function loadStudents(){
        const keyword = document.getElementById('studentSearch').value.trim();
        const tbody = document.getElementById('studentTableBody');
        const empty = document.getElementById('studentEmpty');
        tbody.innerHTML = '';
        empty.style.display = 'none';
        try{
            // 假设接口：GET /teacher/students?keyword=xxx
            // const res = await http(`${API_BASE}/teacher/students?keyword=${encodeURIComponent(keyword)}`);
            // const list = res.data || [];

            // 临时模拟
            const list = [
                {name:'张三', code:'20230001', phone:'13800000001', remain:12},
                {name:'李四', code:'20230002', phone:'13800000002', remain:8}
            ].filter(s=> !keyword || s.name.includes(keyword) || s.code.includes(keyword));

            if(!list.length){ empty.style.display='block'; return; }
            for(const s of list){
                const tr = document.createElement('tr');
                tr.innerHTML = `<td>${s.name}</td><td>${s.code}</td><td>${s.phone}</td><td>${s.remain}</td>`;
                tbody.appendChild(tr);
            }
        }catch(err){
            empty.style.display='block';
            empty.textContent = '加载学生失败，请稍后重试';
        }
    }

    // ========== 上传资料 ==========
    function bindUpload(){
        const form = document.getElementById('uploadForm');
        const msg = document.getElementById('uploadMsg');
        form.addEventListener('submit', async (e)=>{
            e.preventDefault();
            const fileInput = document.getElementById('materialFile');
            const title = document.getElementById('materialTitle').value.trim();
            if(!fileInput.files.length){ showMsg(msg,'请先选择文件','error'); return; }
            if(!title){ showMsg(msg,'请输入资料标题','error'); return; }
            try{
                // 假设接口：POST /materials/upload (multipart/form-data)
                // 这里演示前端校验与成功提示
                showMsg(msg, '上传成功', 'success');
                form.reset();
            }catch(err){
                showMsg(msg, '上传失败：' + err.message, 'error');
            }
        });
    }

    // ========== 下载资料 ==========
    function bindDownload(){
        // 假设接口：GET /materials/list
        const listEl = document.getElementById('materialList');
        // 临时模拟
        const items = [
            {id:1, name:'函数与导数教案.pdf', size:'1.2MB', time:'2025-08-01'},
            {id:2, name:'高一上册数学复习提纲.docx', size:'820KB', time:'2025-08-15'}
        ];
        renderMaterials(items);
        function renderMaterials(items){
            listEl.innerHTML = '';
            if(!items.length){ document.getElementById('materialEmpty').style.display='block'; return; }
            for(const it of items){
                const el = document.createElement('div');
                el.className = 'item';
                el.innerHTML = `
                    <div class="name">${it.name}</div>
                    <div class="meta">大小：${it.size} · 上传时间：${it.time}</div>
                    <div class="actions">
                        <a class="btn btn-secondary" href="${API_BASE}/materials/download/${it.id}" target="_blank">下载</a>
                    </div>`;
                listEl.appendChild(el);
            }
        }
    }

    // ========== 课堂反馈 ==========
    function bindFeedback(){
        const form = document.getElementById('feedbackForm');
        const msg = document.getElementById('feedbackMsg');
        form.addEventListener('submit', async (e)=>{
            e.preventDefault();
            const course = document.getElementById('feedbackCourse').value.trim();
            const text = document.getElementById('feedbackText').value.trim();
            if(!course){ showMsg(msg,'请填写课程/班级信息','error'); return; }
            if(!text){ showMsg(msg,'请填写课堂反馈内容','error'); return; }
            try{
                // 假设接口：POST /teacher/feedback
                // const res = await http(`${API_BASE}/teacher/feedback`, { method:'POST', body: JSON.stringify({course, text}) });
                showMsg(msg, '反馈提交成功', 'success');
                form.reset();
            }catch(err){
                showMsg(msg, '提交失败：' + err.message, 'error');
            }
        });
    }

    // 退出登录
    window.logout = async function(){
        console.log('=== 退出登录开始 ===');
        try {
            // 显示加载状态
            const logoutBtn = document.getElementById('logoutBtn');
            if (!logoutBtn) {
                console.error('未找到退出登录按钮！');
                return;
            }
            
            logoutBtn.disabled = true;
            logoutBtn.textContent = '退出中...';
            console.log('按钮状态已更新为加载中');
            
            // 获取用户token
            const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
            const token = userInfo.token;
            console.log('从localStorage获取的用户信息:', userInfo);
            console.log('获取到的token:', token);
            
            if (!token) {
                console.log('没有token，直接清除本地数据并跳转');
                clearUserDataAndRedirect();
                return;
            }
            
            console.log('准备调用后端退出登录接口:', `${API_BASE}/user/logout`);
            
            // 调用后端退出登录接口
            const response = await fetch(`${API_BASE}/user/logout`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': token
                }
            });
            
            console.log('收到响应:', response);
            console.log('响应状态:', response.status);
            
            if (response.ok) {
                const result = await response.json();
                console.log('响应内容:', result);
                if (result.success) {
                    console.log('退出登录成功');
                    clearUserDataAndRedirect();
                } else {
                    console.error('退出登录失败:', result.errorMsg);
                    clearUserDataAndRedirect();
                }
            } else {
                console.error('退出登录请求失败:', response.status);
                clearUserDataAndRedirect();
            }
            
        } catch (error) {
            console.error('退出登录异常:', error);
            clearUserDataAndRedirect();
        } finally {
            // 恢复按钮状态
            const logoutBtn = document.getElementById('logoutBtn');
            if (logoutBtn) {
                logoutBtn.disabled = false;
                logoutBtn.textContent = '退出登录';
                console.log('按钮状态已恢复');
            }
        }
        console.log('=== 退出登录结束 ===');
    }
    
    // 清除用户数据并跳转
    function clearUserDataAndRedirect() {
        console.log('开始清除用户数据并跳转');
        // 清除所有用户相关数据
        localStorage.removeItem('userInfo');
        localStorage.removeItem('userToken');
        console.log('localStorage数据已清除');
        
        // 跳转到登录页（使用绝对路径，确保从任何页面都能正确跳转）
        console.log('准备跳转到登录页');
        window.location.href = '/login.html';
    }
})(); 